import Link from "next/link";
import { Button } from "antd";
import ResponsiveLayout from "@/components/ResponsiveLayout";
import Footer from "@/components/Footer";
import ShareButton from "@/components/ShareButton";
import ProductScreenshots from "@/components/ProductScreenshots";
import { webAPI } from "@/lib/api";
import type { Product } from "@/lib/api";
import { ArrowUpRightIcon, EyeIcon } from "@heroicons/react/24/outline";
import UserAvatar from "@/components/common/UserAvatar";
import { notFound } from "next/navigation";
import { Metadata } from "next";
import { cache } from "react";

// 生成页面元数据
export async function generateMetadata({ params }: { params: Promise<{ slug: string }> }): Promise<Metadata> {
  const { slug } = await params;
  const product = await getProduct(slug);

  if (!product) {
    return {
      title: "产品不存在 - AI产品之家",
      description: "该产品可能已被删除或移动",
    };
  }

  return {
    title: `${product.title} - AI产品之家`,
    description: product.summary || `${product.title} - 发现好用的AI产品`,
    keywords: [product.title, "AI产品", "人工智能", product.category.name],
    openGraph: {
      title: product.title,
      description: product.summary || `${product.title} - 发现好用的AI产品`,
      images: product.coverImage ? [{ url: product.coverImage, width: 400, height: 400, alt: product.title }] : [],
      type: "website",
      url: `/products/${product.slug}`,
    },
    twitter: {
      card: "summary_large_image",
      title: product.title,
      description: product.summary || `${product.title} - 发现好用的AI产品`,
      images: product.coverImage ? [product.coverImage] : [],
    },
    // 微信专用meta标签
    other: {
      'wechat:title': `${product.title}–AI产品之家`,
      'wechat:description': product.summary || `${product.title} - 发现好用的AI产品`,
      'wechat:image': product.coverImage || '/logo.png',
      'wechat:url': `/products/${product.slug}`,
    },
  };
}

// 获取产品详情数据（使用 cache 避免重复调用）
export const getProduct = cache(async (slug: string): Promise<Product | null> => {
  try {
    const response = await webAPI.getProductBySlug(slug);
    if (response.success) {
      return response.data;
    }
    return null;
  } catch (error) {
    console.error("获取产品详情失败:", error);
    return null;
  }
});

export default async function ProductDetail({ params }: { params: Promise<{ slug: string }> }) {
  const { slug } = await params;
  const product = await getProduct(slug);

  if (!product) {
    notFound();
  }

  // 生成结构化数据
  const structuredData = product
    ? {
        "@context": "https://schema.org",
        "@type": "SoftwareApplication",
        name: product.title,
        description: product.summary || (product.content ? product.content.substring(0, 200) : ""),
        applicationCategory: product.category?.name,
        operatingSystem: "Web",
        url: `${process.env.NEXT_PUBLIC_SITE_URL || "https://aiproducthome.com"}/products/${product.slug}`,
        author: {
          "@type": "Organization",
          name: product.author || "未知作者",
        },
        datePublished: product.publishedAt,
        dateModified: product.updatedAt,
        image: product.coverImage,
        aggregateRating: {
          "@type": "AggregateRating",
          ratingValue: "4.5",
          ratingCount: product.views || 0,
        },
      }
    : null;

  return (
    <ResponsiveLayout active="products">
      {/* 结构化数据 */}
      {structuredData && (
        <script
          type='application/ld+json'
          dangerouslySetInnerHTML={{
            __html: JSON.stringify(structuredData),
          }}
        />
      )}

      <main className='py-8'>
          <div className='container mx-auto px-6'>
            {/* Breadcrumbs */}
            <div className='text-sm text-slate-500 mb-4'>
              <Link href='/' className='hover:underline transition-colors'>
                首页
              </Link>{" "}
              &gt;
              <Link href='/products' className='hover:underline transition-colors'>
                产品
              </Link>
            </div>

            <div className='grid grid-cols-1 lg:grid-cols-3 gap-8'>
              {/* Left Column */}
              <div className='lg:col-span-2 space-y-8'>
                {/* Product Header */}
                <div className='bg-white rounded-xl shadow-md p-6'>
                  <div className='flex flex-col sm:flex-row items-start gap-6'>
                    {/* Logo */}
                    {product.coverImage && <img src={product.coverImage} className='w-20 h-20 sm:w-24 sm:h-24 rounded-lg flex-shrink-0 object-contain' alt={`${product.title} 产品Logo`} />}

                    <div className='flex-grow w-full'>
                      {/* Top row: Title and action buttons */}
                      <div className='flex flex-col md:flex-row justify-between md:items-start gap-4'>
                        <div className='flex-grow'>
                          <h1 className='text-2xl font-bold text-slate-900'>{product.title}</h1>
                          {/* Tagline */}
                          <p className='mt-1 text-slate-600'>{product.summary}</p>
                        </div>
                        <div className='flex items-center flex-wrap gap-2 flex-shrink-0'>
                          <ShareButton 
                            title={`${product.title} - AI产品之家`}
                            description={product.summary}
                            imageUrl={product.coverImage}
                          />
                          {product.websiteUrl && (
                            <Button href={product.websiteUrl} target='_blank' rel='noopener noreferrer' className='text-sm bg-yellow-400 text-white font-bold py-2 px-4 rounded-md hover:bg-yellow-500 transition-all duration-200 flex items-center gap-1' icon={<ArrowUpRightIcon className='w-4 h-4' />} color='yellow'>
                              访问官网
                            </Button>
                          )}
                        </div>
                      </div>

                      {/* Bottom row: Stats */}
                      <div className='mt-4 flex flex-col sm:flex-row sm:items-center gap-4 text-sm'>
                        <div className='flex items-center space-x-4 text-slate-500 mt-2 sm:mt-0 sm:ml-auto'>
                          <EyeIcon className='w-4 h-4 mr-1' />
                          <span> {product.views} 浏览</span>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>

                {/* Product Screenshots */}
                {product.screenshots && product.screenshots.length > 0 && (
                  <ProductScreenshots 
                    screenshots={product.screenshots} 
                    productTitle={product.title}
                  />
                )}

                {/* Product Description */}
                <div className='bg-white rounded-xl shadow-md p-6 md:p-8'>
                  <h2 className='text-2xl font-bold mb-4 text-slate-800'>产品简介</h2>
                  <div className='prose prose-slate max-w-none'>
                    <div className='w-e-text-container text-sm text-slate-700 leading-relaxed' dangerouslySetInnerHTML={{ __html: product.content }} />
                  </div>
                </div>
              </div>

              {/* Right Sidebar */}
              <div className='lg:col-span-1 space-y-8'>
                <aside className='bg-white rounded-xl shadow-md p-6'>
                  <h3 className='font-bold text-lg mb-4 border-b border-slate-200 pb-3 text-slate-800'>开发者</h3>
                  <div className='flex items-start space-x-4'>
                    <UserAvatar src={product.developerAvatar} alt={`${product.developerNickname || product.author} 头像`} size={64} showBorder={true} />
                    <div className='flex-grow min-w-0 flex items-center h-16'>
                      <p className='font-bold text-slate-800 text-lg mb-1 line-clamp-2 w-full'>{product.developerNickname || product.author}</p>
                    </div>
                  </div>
                  {product.developerBio && (
                    <div className='mt-4 p-4 bg-slate-50 rounded-lg border border-slate-200'>
                      <h4 className='text-sm font-semibold text-slate-700 mb-2'>关于开发者</h4>
                      <p className='text-sm text-slate-600 leading-relaxed whitespace-pre-wrap'>{product.developerBio}</p>
                    </div>
                  )}
                </aside>
              </div>
            </div>
          </div>
        </main>
        {/* Footer */}
        <Footer />
    </ResponsiveLayout>
  );
}
